package com.springmvc.controller;

import com.springmvc.pojo.MultiFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class FileUploadController {

    @RequestMapping("/fileUpload")
    public String fileupload(@ModelAttribute MultiFile multiFile, HttpServletRequest request) throws IOException {
//        String filename = photo.getOriginalFilename();
//        System.out.println(filename);
//        ServletContext servletContext = session.getServletContext();
//        String realPath = "E:/springmvc/Upload";
//        File file = new File(realPath);
//        System.out.println(file);
//        //判断realPath对应的路径是否存在
//        if (!file.exists()){
//            //不存在就创建
//            file.mkdir();
//        }
//        String finalPath = realPath + File.separator + filename;
//        photo.transferTo(new File(finalPath));
        //上传位置
        String path = "E:\\springmvc\\Upload";
        //判断该路径是否存在
        File file = new File(path);
        if(!file.exists()){
            //创建该文件夹
            file.mkdirs();
        }
        List<MultipartFile> list = multiFile.getList();
        for(int i=0;i<list.size();i++){
            MultipartFile file1 = list.get(i);
            String filename = file1.getOriginalFilename();
            System.out.println("获取的第"+(i+1)+"文件名为:"+filename);
            if(!filename.isEmpty()){
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid+filename;
                //完成文件的上传
                file1.transferTo(new File(path,filename));
            }
        }
        return "fileUpload";
    }
}

